const Router = require("koa-router")
const router = new Router({
    prefix: "/v1/blog"
})
const sequelize = require("../../core/db")
const { Op } = require("sequelize")
const auth = require("../../middleware/auth")
const { Blog, User, Img } = require("../../model/index")
const { Success, CustomError } = require("../../core/common")

//上传博客
router.post("/addBlog", auth, async ctx => {
    const { user } = ctx.auth
    const { content, imgList } = ctx.request.body

    //托管事务
    await sequelize.transaction(async(t) => {
        const blog = await Blog.create({
            content
        }, { transaction: t })
        await user.addBlog(blog, { transaction: t })
        let _imgList = imgList.map(item => ({ url: item.url }))
        const imageList = await Img.bulkCreate(_imgList, { transaction: t })
        await blog.addImgs(imageList, { transaction: t })
        Success(ctx, "创建博客成功")
    })

})
router.get("/test/haha", async ctx => {
        ctx.body = {
            test: "hahah"
        }
    })
    //获取博客列表(登入态)
router.get("/getBlogsWithToken", auth, async ctx => {
        const { key, page, perPageCount } = ctx.request.query
        const { user } = ctx.auth
        const offset = parseInt(perPageCount) * (parseInt(page) - 1)
        const groups = await user.getGroups({ where: { key } })
        const groupName = groups[0].name
        switch (groupName) {
            default: const followIds = (await user.getFollow()).map(item => item.uid)
            const { count, rows } = await Blog.findAndCountAll({
                where: {
                    UserUid: {
                        [Op.in]: followIds
                    }
                },
                include: [User, Img],
                order: [
                    ['createdAt', 'DESC']
                ],
                limit: parseInt(perPageCount),
                offset
            })
            const blogList = rows.map(item => Object.assign({}, item.toJSON(), { userInfo: item.User.userInfo }, { blogImgs: item.Imgs.map(item => item.toJSON()) }))
            Success(ctx, {
                count,
                blogList,
                currentPage: parseInt(page)
            })
            break;

        }

    })
    //获取博客列表(无登入态)
router.get("/getBlogs", async ctx => {
    const { page, perPageCount } = ctx.request.query
    const offset = parseInt(perPageCount) * (parseInt(page) - 1)
    const { count, rows } = await Blog.findAndCountAll({
        include: [User, Img],
        order: [
            ['createdAt', 'DESC']
        ],
        limit: parseInt(perPageCount),
        offset
    })
    const blogList = rows.map(item => Object.assign({}, item.toJSON(), { userInfo: item.User.userInfo }, { blogImgs: item.Imgs.map(item => item.toJSON()) }))
    Success(ctx, {
        count,
        blogList,
        currentPage: parseInt(page)
    })
})

module.exports = router